import type { inputProps, formateType, rangeType, currentValueType } from './input.type'
import { ref, watch } from 'vue'

export const useInput = (props: inputProps) => {
  const formate: formateType = (value) => {
    value = String(value)
      .replace(/[^\d.]/g, '')
      .replace(/^\./g, '')
      .replace(/\.{2,}/g, '.')
      .replace('.', '$#$')
      .replace(/\./g, '')
      .replace('$#$', '.')
      .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      return value === '' ? '' :  props.integer ? String(Math.floor(+value) ): value
  }
  
  const range: rangeType = (value) => {
    return value === '' ? '' : Math.max(Math.min(+props.max, +value), +props.min)
  }

  const initValue = props.initValue || props.modelValue

  const currentValue = ref<currentValueType>(range(formate(initValue)))

  const handleInput = (event: Event) => {
    const input = event.target as HTMLInputElement
    const { value } = input
    const formated = formate(value)
    input.value = formated
    currentValue.value = +formated
  }

  const handleBlur = (event: Event) => {
    const input = event.target as HTMLInputElement
    const { value } = input
    const ranged = range(value)
    currentValue.value = ranged
    if (+value !== ranged) {
      input.value = String(ranged)
    }
  }

  const resetValue = () => {
    currentValue.value = range(formate(currentValue.value))
  }

  watch(
    [
      () => props.min,
      () => props.max
    ],
    resetValue
  )

  return {
    handleInput,
    handleBlur,
    currentValue
  }

}